package com.lz.sports.dialog

import android.app.Dialog
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import com.lz.comm.SP
import com.lz.library.dialog.BaseDialogFragment
import com.lz.library.extension.countDown
import com.lz.library.extension.dp2px
import com.lz.sports.R
import com.lz.sports.core.*
import com.lz.sports.databinding.DialogDowntimeBinding
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.onCompletion
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch

//开始考试倒计时准备
class DowntimeDialog : BaseDialogFragment<DialogDowntimeBinding>() {

    companion object {
        fun show(activity: FragmentActivity, time: Int): DowntimeDialog {
            val dialog = DowntimeDialog().also {
                it.arguments = Bundle().apply { putInt("time", time) }
            }
            dialog.setFrom(true)
            dialog.show(activity.supportFragmentManager)
            return dialog
        }
    }

    private val soundHelper by lazy { SoundHelper() }

    //自动播报
    private var soundAuto = false


    override fun getLayoutRes(): Int = R.layout.dialog_downtime

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        soundHelper.init(intArrayOf(R.raw.one, R.raw.two, R.raw.three))
        soundAuto = SP.getBoolean(K_SOUND_AUTO, v_sound_auto) && SP.getBoolean(K_SOUND_PRE, v_sound_pre)
    }

    override fun onDestroy() {
        super.onDestroy()
        soundHelper.release()
    }

    override fun initData(v: View, savedState: Bundle?) {
        val time = arguments!!.getInt("time")
        lifecycleScope.launch {
            countDown(time).onStart {
                binding.tvTime.text = "$time"
            }.onCompletion {
                dismiss()
            }.collect {
                binding.tvTime.text = "$it"
                if (soundAuto && it in 1..3) {
                    soundHelper.play(it - 1)
                }
            }
        }
    }

    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog = object : BaseDialog(requireContext(), outsideCancel = false) {
        override fun initParams(params: WindowManager.LayoutParams) {
            params.width = 72.dp2px()
            params.height = 72.dp2px()
            params.gravity = Gravity.CENTER
        }
    }

}